package com.xzz;

/**
 * @author 黄会准
 * @since 2020-11-10
 */

/**
 * 两数相加
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 */
public class TwoAdd {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        printListNode(l1);
        printListNode(l2);
        printListNode(addTwoNumbers(l1, l2));
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        boolean flag = false;
        ListNode l3 = null, temp = null;
        while (l1 != null || l2 != null) {
            int sum = 0;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            if (flag) {
                sum++;
            }
            flag = sum >= 10 ? true : false;
            if (l3 == null) {
                l3 = temp = new ListNode(sum % 10);
            } else {
                temp.next = new ListNode(sum % 10);
                temp = temp.next;
            }
        }
        if (flag) {
            temp.next = new ListNode(1);
        }
        return l3;
    }

    public static void printListNode(ListNode l) {
        while (l != null) {
            if (l.next != null) {
                System.out.print(l.val + "->");
            } else {
                System.out.println(l.val);
            }
            l = l.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
